package projects.android.sms.activities;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;

import projects.android.sms.R;
import projects.android.sms.db.DBHandle;
import projects.android.sms.encrypter.Encrypter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * Activity showing a fancy splashscreen and generating the own key pair if it does not exist yet (most likely at the
 * first app launch).
 * 
 * @author Thomas Jaeger
 * @author Mario Kraml
 * @author Tassilo Posegga
 * @author Robert Schenkenfelder
 * 
 */
public class SplashScreenActivity extends Activity {

	final String TAG = "SplashScreenActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_layout);

		DBHandle db = DBHandle.getInstance(getApplicationContext());
		RSAPublicKey pubKey = db.getOwnPublicKey();

		if (pubKey == null) {
			// This is the first start of the App - generate KeyPair
			Log.e(TAG, "First app start, generate and store KeyPair");

			KeyPair kp = Encrypter.generateKeyPair();
			RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
			RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) kp.getPrivate();

			Log.i(TAG, "public key: modulus = " + publicKey.getModulus().toString(16) + ", exponent = "
					+ publicKey.getPublicExponent().toString(16));

			db.setOwnKeyPair(privateKey, publicKey);
		}

		Thread timer = new Thread() {
			@Override
			public void run() {
				try {
					sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					Intent intent = new Intent(getApplicationContext(), InboxActivity.class);
					startActivity(intent);
					finish();
				}
			}
		};
		timer.start();
	}
}
